from flask import Flask, render_template, request, escape
import geo
import driving

app = Flask(__name__)


@app.route('/')
@app.route('/entry')
def entry01() -> 'html':
    title = '很荣幸为您提供驾车路径规划服务！'
    return render_template('entry.html',
                           the_title = title)



@app.route('/results', methods=['POST'])
def results01() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '搜索结果'
    df = driving.driving01(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration', 'action']]
    results.columns = ['指引', '路程', '时间', '弯道']
    total_driving = driving.total_driving(df)
    total_driving_time = driving.total_driving_time(df)
    route = results['指引'].tolist()
    driving.log_request(request, route)
    return render_template('results.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html=results.to_html(index=False),
                           the_total_driving=total_driving,
                           the_total_driving_time=total_driving_time,)


@app.route('/log', methods=['POST'])
def log01() -> 'html':
    contents = []
    with open('driving.log', 'r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('用户输入数据', '远程地址', '用户代理', '搜索结果')
    return render_template('log.html',
                           the_title='查看日志',
                           the_row_titles=titles,
                           the_data=contents, )


if __name__ == '__main__':
    app.run()
